/**
 * 信任触控反馈管理器
 * 管理信任卡牌的触控交互和反馈效果
 */

class TrustTouchManager {
  constructor() {
    this.touchConfig = {
      longPressThreshold: 1000, // 长按阈值（毫秒）
      swipeThreshold: 50, // 滑动阈值（像素）
      doubleTapThreshold: 300, // 双击阈值（毫秒）
      touchHintDelay: 500, // 触控提示延迟（毫秒）
      vibrationEnabled: true, // 震动反馈
      soundEnabled: true // 声音反馈
    }
    
    this.touchHistory = []
    this.gestureRecognizers = new Map()
    this.initGestureRecognizers()
  }

  /**
   * 初始化手势识别器
   */
  initGestureRecognizers() {
    // 点击识别器
    this.gestureRecognizers.set('tap', {
      minDuration: 50,
      maxDuration: 300,
      maxDistance: 10
    })
    
    // 长按识别器
    this.gestureRecognizers.set('longPress', {
      minDuration: this.touchConfig.longPressThreshold,
      maxDistance: 20
    })
    
    // 滑动识别器
    this.gestureRecognizers.set('swipe', {
      minDistance: this.touchConfig.swipeThreshold,
      maxDuration: 500
    })
    
    // 双击识别器
    this.gestureRecognizers.set('doubleTap', {
      maxInterval: this.touchConfig.doubleTapThreshold,
      maxDistance: 20
    })
  }

  /**
   * 处理触控开始
   */
  handleTouchStart(touch, cardData) {
    const touchRecord = {
      id: Date.now(),
      startTime: Date.now(),
      startPos: { x: touch.clientX, y: touch.clientY },
      currentPos: { x: touch.clientX, y: touch.clientY },
      cardId: cardData.id,
      status: 'started'
    }
    
    this.touchHistory.push(touchRecord)
    
    // 触发触控开始事件
    this.emitTouchEvent('touchStart', {
      touch: touchRecord,
      card: cardData
    })
    
    // 开始触控提示
    this.startTouchHint(touchRecord, cardData)
    
    return touchRecord
  }

  /**
   * 处理触控移动
   */
  handleTouchMove(touch, touchRecord) {
    if (!touchRecord) return
    
    touchRecord.currentPos = { x: touch.clientX, y: touch.clientY }
    touchRecord.duration = Date.now() - touchRecord.startTime
    
    const deltaX = touchRecord.currentPos.x - touchRecord.startPos.x
    const deltaY = touchRecord.currentPos.y - touchRecord.startPos.y
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
    
    touchRecord.distance = distance
    touchRecord.direction = this.getDirection(deltaX, deltaY)
    
    // 检测手势类型
    const gesture = this.detectGesture(touchRecord)
    if (gesture && gesture !== touchRecord.gesture) {
      touchRecord.gesture = gesture
      this.handleGestureChange(touchRecord, gesture)
    }
    
    // 触发触控移动事件
    this.emitTouchEvent('touchMove', {
      touch: touchRecord,
      gesture: gesture
    })
    
    return touchRecord
  }

  /**
   * 处理触控结束
   */
  handleTouchEnd(touch, touchRecord) {
    if (!touchRecord) return
    
    touchRecord.endTime = Date.now()
    touchRecord.duration = touchRecord.endTime - touchRecord.startTime
    touchRecord.status = 'ended'
    
    // 最终手势检测
    const finalGesture = this.detectGesture(touchRecord)
    touchRecord.gesture = finalGesture
    
    // 处理手势
    this.handleGesture(touchRecord, finalGesture)
    
    // 触发触控结束事件
    this.emitTouchEvent('touchEnd', {
      touch: touchRecord,
      gesture: finalGesture
    })
    
    return touchRecord
  }

  /**
   * 检测手势类型
   */
  detectGesture(touchRecord) {
    const { duration, distance, startPos, currentPos } = touchRecord
    
    // 检测长按
    if (duration >= this.touchConfig.longPressThreshold && distance < 20) {
      return 'longPress'
    }
    
    // 检测滑动
    if (distance >= this.touchConfig.swipeThreshold && duration < 500) {
      return 'swipe'
    }
    
    // 检测点击
    if (duration < 300 && distance < 10) {
      return 'tap'
    }
    
    return 'unknown'
  }

  /**
   * 处理手势变化
   */
  handleGestureChange(touchRecord, gesture) {
    switch (gesture) {
      case 'swipe':
        this.handleSwipeStart(touchRecord)
        break
      case 'longPress':
        this.handleLongPressStart(touchRecord)
        break
    }
  }

  /**
   * 处理手势
   */
  handleGesture(touchRecord, gesture) {
    switch (gesture) {
      case 'tap':
        this.handleTap(touchRecord)
        break
      case 'longPress':
        this.handleLongPress(touchRecord)
        break
      case 'swipe':
        this.handleSwipe(touchRecord)
        break
    }
  }

  /**
   * 处理点击
   */
  handleTap(touchRecord) {
    // 检查双击
    const recentTaps = this.touchHistory.filter(t => 
      t.gesture === 'tap' && 
      t.endTime && 
      (touchRecord.startTime - t.endTime) < this.touchConfig.doubleTapThreshold
    )
    
    if (recentTaps.length > 0) {
      this.handleDoubleTap(touchRecord)
    } else {
      this.emitTouchEvent('tap', { touch: touchRecord })
      this.triggerFeedback('tap', touchRecord)
    }
  }

  /**
   * 处理双击
   */
  handleDoubleTap(touchRecord) {
    this.emitTouchEvent('doubleTap', { touch: touchRecord })
    this.triggerFeedback('doubleTap', touchRecord)
  }

  /**
   * 处理长按开始
   */
  handleLongPressStart(touchRecord) {
    this.emitTouchEvent('longPressStart', { touch: touchRecord })
    this.triggerFeedback('longPressStart', touchRecord)
  }

  /**
   * 处理长按
   */
  handleLongPress(touchRecord) {
    this.emitTouchEvent('longPress', { touch: touchRecord })
    this.triggerFeedback('longPress', touchRecord)
  }

  /**
   * 处理滑动开始
   */
  handleSwipeStart(touchRecord) {
    this.emitTouchEvent('swipeStart', { touch: touchRecord })
    this.triggerFeedback('swipeStart', touchRecord)
  }

  /**
   * 处理滑动
   */
  handleSwipe(touchRecord) {
    this.emitTouchEvent('swipe', { touch: touchRecord })
    this.triggerFeedback('swipe', touchRecord)
  }

  /**
   * 获取方向
   */
  getDirection(deltaX, deltaY) {
    const absX = Math.abs(deltaX)
    const absY = Math.abs(deltaY)
    
    if (absX > absY) {
      return deltaX > 0 ? 'right' : 'left'
    } else {
      return deltaY > 0 ? 'down' : 'up'
    }
  }

  /**
   * 开始触控提示
   */
  startTouchHint(touchRecord, cardData) {
    setTimeout(() => {
      if (touchRecord.status === 'started') {
        this.emitTouchEvent('touchHint', {
          touch: touchRecord,
          card: cardData,
          hint: this.getTouchHint(cardData)
        })
      }
    }, this.touchConfig.touchHintDelay)
  }

  /**
   * 获取触控提示
   */
  getTouchHint(cardData) {
    const hints = {
      high: '高度信任，点击查看详情',
      medium: '一般信任，长按预览效果',
      low: '低度信任，滑动选择操作',
      broken: '信任破裂，需要修复'
    }
    
    const trustLevel = this.getTrustLevel(cardData.trustValue)
    return hints[trustLevel] || '点击查看详情'
  }

  /**
   * 获取信任等级
   */
  getTrustLevel(trustValue) {
    if (trustValue >= 80) return 'high'
    if (trustValue >= 50) return 'medium'
    if (trustValue >= 20) return 'low'
    return 'broken'
  }

  /**
   * 触发反馈
   */
  triggerFeedback(type, touchRecord) {
    const feedback = this.getFeedbackConfig(type, touchRecord)
    
    // 震动反馈
    if (this.touchConfig.vibrationEnabled && feedback.vibration) {
      this.triggerVibration(feedback.vibration)
    }
    
    // 声音反馈
    if (this.touchConfig.soundEnabled && feedback.sound) {
      this.triggerSound(feedback.sound)
    }
    
    // 视觉反馈
    if (feedback.visual) {
      this.triggerVisualFeedback(feedback.visual, touchRecord)
    }
  }

  /**
   * 获取反馈配置
   */
  getFeedbackConfig(type, touchRecord) {
    const configs = {
      tap: {
        vibration: { duration: 50, intensity: 0.5 },
        sound: 'tap',
        visual: { type: 'ripple', duration: 300 }
      },
      doubleTap: {
        vibration: { duration: 100, intensity: 0.7 },
        sound: 'doubleTap',
        visual: { type: 'doubleRipple', duration: 500 }
      },
      longPress: {
        vibration: { duration: 200, intensity: 0.8 },
        sound: 'longPress',
        visual: { type: 'glow', duration: 1000 }
      },
      swipe: {
        vibration: { duration: 30, intensity: 0.3 },
        sound: 'swipe',
        visual: { type: 'trail', duration: 400 }
      }
    }
    
    return configs[type] || {}
  }

  /**
   * 触发震动
   */
  triggerVibration(config) {
    if (typeof navigator !== 'undefined' && navigator.vibrate) {
      navigator.vibrate(config.duration)
    }
  }

  /**
   * 触发声音
   */
  triggerSound(soundType) {
    // 这里可以播放相应的声音文件
    console.log(`Playing sound: ${soundType}`)
  }

  /**
   * 触发视觉反馈
   */
  triggerVisualFeedback(config, touchRecord) {
    this.emitTouchEvent('visualFeedback', {
      config,
      touch: touchRecord
    })
  }

  /**
   * 触发触控事件
   */
  emitTouchEvent(eventType, data) {
    if (typeof window !== 'undefined' && window.dispatchEvent) {
      const event = new CustomEvent('trustTouch', {
        detail: { eventType, data }
      })
      window.dispatchEvent(event)
    }
  }

  /**
   * 设置触控配置
   */
  setTouchConfig(config) {
    this.touchConfig = { ...this.touchConfig, ...config }
    this.initGestureRecognizers()
  }

  /**
   * 获取触控统计
   */
  getTouchStats() {
    const stats = {
      totalTouches: this.touchHistory.length,
      gestures: {},
      averageDuration: 0,
      mostCommonGesture: null
    }
    
    // 统计手势
    this.touchHistory.forEach(touch => {
      if (touch.gesture) {
        stats.gestures[touch.gesture] = (stats.gestures[touch.gesture] || 0) + 1
      }
    })
    
    // 计算平均持续时间
    const completedTouches = this.touchHistory.filter(t => t.duration)
    if (completedTouches.length > 0) {
      stats.averageDuration = completedTouches.reduce((sum, t) => sum + t.duration, 0) / completedTouches.length
    }
    
    // 找出最常见的手势
    const gestureCounts = Object.entries(stats.gestures)
    if (gestureCounts.length > 0) {
      stats.mostCommonGesture = gestureCounts.reduce((a, b) => a[1] > b[1] ? a : b)[0]
    }
    
    return stats
  }

  /**
   * 清除触控历史
   */
  clearTouchHistory() {
    this.touchHistory = []
  }

  /**
   * 启用/禁用反馈
   */
  setFeedbackEnabled(type, enabled) {
    if (type === 'vibration') {
      this.touchConfig.vibrationEnabled = enabled
    } else if (type === 'sound') {
      this.touchConfig.soundEnabled = enabled
    }
  }
}

// 创建单例实例
const trustTouchManager = new TrustTouchManager()

export default trustTouchManager

